package com.lagou.filter;

import com.lagou.model.TPData;
import com.lagou.monitor.TPDataMonitor;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.ScheduledThreadPoolExecutor;

@Activate(group = CommonConstants.CONSUMER)
public class TPMonitorFilter implements Filter {

    //单例
    TPDataMonitor tpDataMonitor = TPDataMonitor.getInstance();

    //为了保证准时输出统计数据，filter的invoke方法中应该只负责获取和存储数据，统计应该交给其他线程处理
    //Consumer是通过依赖的方式加载filter的, 尝试在Consumer中调用calcTP90/calcTP99方法
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        Result result = null;
        long duration = 0L;

        long startTime = System.currentTimeMillis();
        try {
            result = invoker.invoke(invocation);
            duration = System.currentTimeMillis() - startTime;

        } catch (RpcException e) {
            duration = System.currentTimeMillis() - startTime;
            e.printStackTrace();
        }

        String methodName = invocation.getMethodName();

//        System.out.println(methodName + ": " + duration + "ms");

        if("methodA".equals(methodName)){
            tpDataMonitor.queueA.add(new TPData(System.currentTimeMillis(), duration));
        }else if("methodB".equals(methodName)){
            tpDataMonitor.queueB.add(new TPData(System.currentTimeMillis(), duration));
        }else if("methodC".equals(methodName)){
            tpDataMonitor.queueC.add(new TPData(System.currentTimeMillis(), duration));
        }else{
            System.out.println("异常方法调用");
        }

        return result;
    }
}
